const Router = require('koa-router')
const fs = require('fs')
const { resDesign } = require('@/utils/dataDesign')
const { APP_HOST, APP_PORT } = require('@/app/config')
const { resAvatarPath, resPicturePath } = require('@/constants/file-path')
const { avatarHandler, pictureHandler } = require('@/middleware/file.mid')
const SystemService = require('@/service/system.service')
const { existsSync, mkdirSync } = require('fs')

const fileRouter = new Router()

// 上传头像
fileRouter.post(
  '/upload/avatar',
  async (ctx, next) => {
    try {
      const path = resAvatarPath()
      const flag = await existsSync(path)
      if (!flag) {
        await mkdirSync(path)
      }
      ctx.filePath = path
      await next()
    } catch (error) {
      console.log(error)
      ctx.body = {
        path,
        error,
      }
    }
  },
  avatarHandler,
  async (ctx) => {
    try {
      // 1.获取图像相关的信息
      const { filename, mimetype, size } = ctx.req.file
      const { id } = ctx.user
      const path = ctx.filePath

      // 2.将图像信息数据保存到数据库中
      await SystemService.createAvatar(filename, mimetype, size, id, path)

      // 3.将图片地址保存到user表中
      const avatarUrl = `${APP_HOST}:${APP_PORT}/users/avatar/${id}`
      await SystemService.updateAvatarUrlById(avatarUrl, id)

      ctx.body = resDesign({ msg: '头像已上传', data: { url: avatarUrl, mimetype, filename, size } })
    } catch (error) {
      console.log(error)
      ctx.body = error
    }
  }
)

// 获取头像
fileRouter.get('/users/avatar/:id', async (ctx) => {
  try {
    // 1.用户的头像是哪一个文件?
    const { id } = ctx.params
    const avatarInfo = await SystemService.getAvatarByUserId(id)

    // 2.提供图像信息
    ctx.response.set('content-type', avatarInfo.mimeType)
    ctx.body = fs.createReadStream(`${avatarInfo.path}/${avatarInfo.filename}`)
  } catch (error) {
    console.log(error)
  }
})

// 上传图片
fileRouter.post(
  '/upload/picture',
  async (ctx, next) => {
    try {
      const path = resPicturePath()
      const flag = await existsSync(path)
      if (!flag) {
        await mkdirSync(path)
      }
      ctx.filePath = path
      await next()
    } catch (error) {
      console.log(error)
      ctx.body = {
        path,
        error,
      }
    }
  },
  pictureHandler,
  async (ctx) => {
    try {
      // 1.获取图像信息
      const files = ctx.req.files
      const { id } = ctx.user
      const path = ctx.filePath
      const data = []

      // 2.将所有的文件信息保存到数据库中
      for (let file of files) {
        const { filename, mimetype, size } = file
        await SystemService.createPicture(filename, mimetype, size, id, path)
        data.push({
          url: `${APP_HOST}:${APP_PORT}/system/images/${filename}`,
          filename,
          mimetype,
          size,
        })
      }

      ctx.body = resDesign({ msg: '图片已上传', data })
    } catch (error) {
      console.log(error)
      ctx.body = error
    }
  }
)

// 获取图片
fileRouter.get('/system/images/:filename', async (ctx) => {
  try {
    let { filename } = ctx.params
    const fileInfo = await SystemService.getPictureByFilename(filename)
    const { type } = ctx.query
    const types = ['small', 'middle', 'large']
    if (types.some((item) => item === type)) {
      filename = filename + '-' + type
    }
    ctx.response.set('content-type', fileInfo.mimetype)
    ctx.body = fs.createReadStream(`${fileInfo.path}/${filename}`)
  } catch (error) {
    console.log(error)
    ctx.body = error
  }
})

module.exports = fileRouter
